import React, { useState } from 'react';
import { Card, Button, Typography, Alert, Space } from 'antd';
import { fetchProtectedData } from '../../api/auth';

const { Title, Text } = Typography;

// 添加ProtectedContent组件的props接口
interface ProtectedContentProps {
  isAuthenticated: boolean;
  data?: { message: string } | null;
  onFetchData: () => Promise<void>;
}

const ProtectedContent = ({ isAuthenticated, data, onFetchData }: ProtectedContentProps) => {
  const [loading, setLoading] = useState(false);
  
  const handleFetch = async () => {
    setLoading(true);
    try {
      await onFetchData();
    } catch (error) {
      console.error('Fetch failed', error);
    } finally {
      setLoading(false);
    }
  };

  if (!isAuthenticated) {
    return (
      <Card title="受保护内容">
        <Alert 
          message="未认证用户" 
          description="请先登录以访问受保护内容" 
          type="warning"
          showIcon
        />
      </Card>
    );
  }

  return (
    <Card 
      title="受保护内容" 
      extra={
        <Button 
          type="primary" 
          onClick={handleFetch}
          loading={loading}
        >
          获取内容
        </Button>
      }
    >
      {data ? (
        <div>
          <Title level={5} style={{ marginTop: 0 }}>服务器响应:</Title>
          <Text>{data.message}</Text>
        </div>
      ) : (
        <Space direction="vertical" style={{ width: '100%' }}>
          <Alert 
            message="内容未加载" 
            description="点击上方按钮获取受保护内容" 
            type="info"
            showIcon
          />
        </Space>
      )}
    </Card>
  );
};

// 添加ProtectedModule组件的props接口
interface ProtectedModuleProps {
  isAuthenticated: boolean;
  protectedData?: { message: string } | null;
  onFetchData: () => Promise<void>;
}

const ProtectedModule = ({ isAuthenticated, protectedData, onFetchData }: ProtectedModuleProps) => {
  return (
    <div style={{ marginBottom: 24 }}>
      <ProtectedContent 
        isAuthenticated={isAuthenticated}
        data={protectedData}
        onFetchData={onFetchData}
      />
    </div>
  );
};

export default ProtectedModule;